package Thread.CasOp;

import java.util.concurrent.atomic.AtomicInteger;
//原子类的理解
//CAS  compare and swap  比较并交换
//CAS  三个操作数  内存值V  预期值A  更新值B
//当且仅当内存值V等于预期值A时，将内存值V修改为B，否则什么都不做
//虽然没有加锁，但是也保证了线程安全
//AtomicInteger  原子类
//底层是CAS操作
//AtomicInteger  底层是volatile修饰的int类型变量
//volatile 保证了内存可见性
public class Demo40 {
//    private static int count = 0;
    private static AtomicInteger count = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                //count++;
//                count.incrementAndGet();//++count
//                count.getAndIncrement();//count++
//                count.getAndDecrement();//count--
                count.decrementAndGet();//--count
//                count.addAndGet(1);//count+=1
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                //count++;
                count.incrementAndGet();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count ="+count.get());
    }
}

